package cn.com.css.taxInspection.ajgl.controller;

import cn.com.css.taxInspection.attention.entity.AjglCfjdsqcEntity;
import cn.com.css.taxInspection.attention.entity.AjglCljdsqcEntity;
import cn.com.css.taxInspection.attention.service.AjglCfjdsqcService;
import cn.com.css.taxInspection.attention.service.AjglCljdsqcService;
import cn.com.css.taxInspection.common.aop.annotation.LogAnnotation;
import cn.com.css.taxInspection.common.result.Result;
import cn.hutool.core.convert.Convert;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 案件管理-处理决定书清册
 */
@RequestMapping("/ajgl")
@RestController
@Api(tags = "处理决定书清册")
public class AjglController {

    private static final Logger log = LoggerFactory.getLogger(AjglController.class);

    @Resource
    private AjglCljdsqcService ajglCljdsqcService;

    @Resource
    private AjglCfjdsqcService ajglCfjdsqcService;

    @PostMapping("/cljds/importCljdsData")
    @ApiOperation(value = "处理决定书清册-批量导入纳税人识别号查询功能")
    @LogAnnotation(title = "处理决定书清册", action = "批量导入纳税人识别号查询功能")
    public ResponseEntity<?> importCljdsData(@RequestParam(value = "file") MultipartFile file) {

        if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
            return ResponseEntity.ok(Result.error("上传的文件为空！"));
        }

        try (ExcelReader reader = ExcelUtil.getReader(file.getInputStream())) {
            // 2. 读取所有数据（跳过表头行）
            List<List<Object>> rows = reader.read(1, reader.getRowCount()); // 从第2行开始读

            // 3. 提取纳税人识别号（第1列）并去重
            Set<String> nsrsbhSet = rows.stream()
                    .filter(row -> row != null && !row.isEmpty()) // 过滤空行
                    .map(row -> Convert.toStr(row.get(0), ""))   // 取第1列并转String
                    .filter(StringUtils::isNotBlank)             // 过滤空值
                    .collect(Collectors.toCollection(LinkedHashSet::new)); // 自动去重

            // 4. 检查有效数据
            if (nsrsbhSet.isEmpty()) {
                return ResponseEntity.ok(Result.error("Excel 中没有有效的纳税人识别号！"));
            }

            List<String> nsrsbhList = new ArrayList<>(nsrsbhSet);
            AjglCljdsqcEntity ajglCljdsqcEntity = new AjglCljdsqcEntity();
            ajglCljdsqcEntity.setNsrsbhList(nsrsbhList);
            // 5. 调用Service进行IN查询
            IPage<AjglCljdsqcEntity> ajglCljdsqcEntityIPage = ajglCljdsqcService.queryCljdsTable(ajglCljdsqcEntity);
            // 封装返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("pageData", ajglCljdsqcEntityIPage);  // 分页数据
            result.put("nsrsbhList", nsrsbhList);           // 纳税人识别号列表
            return ResponseEntity.ok(Result.success(result));
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            return ResponseEntity.ok(Result.error("解析文件失败：" + e.getMessage()));
        }
    }

    @PostMapping("/cfjds/importCfjdsData")
    @ApiOperation(value = "处罚决定书清册-批量导入纳税人识别号查询功能")
    @LogAnnotation(title = "处罚决定书清册", action = "批量导入纳税人识别号查询功能")
    public ResponseEntity<?> importCfjdsData(@RequestParam(value = "file") MultipartFile file) {

        if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
            return ResponseEntity.ok(Result.error("上传的文件为空！"));
        }

        try (ExcelReader reader = ExcelUtil.getReader(file.getInputStream())) {
            // 2. 读取所有数据（跳过表头行）
            List<List<Object>> rows = reader.read(1, reader.getRowCount()); // 从第2行开始读

            // 3. 提取纳税人识别号（第1列）并去重
            Set<String> nsrsbhSet = rows.stream()
                    .filter(row -> row != null && !row.isEmpty()) // 过滤空行
                    .map(row -> Convert.toStr(row.get(0), ""))   // 取第1列并转String
                    .filter(StringUtils::isNotBlank)             // 过滤空值
                    .collect(Collectors.toCollection(LinkedHashSet::new)); // 自动去重

            // 4. 检查有效数据
            if (nsrsbhSet.isEmpty()) {
                return ResponseEntity.ok(Result.error("Excel 中没有有效的纳税人识别号！"));
            }

            List<String> nsrsbhList = new ArrayList<>(nsrsbhSet);
            AjglCfjdsqcEntity ajglCfjdsqcEntity = new AjglCfjdsqcEntity();
            ajglCfjdsqcEntity.setNsrsbhList(nsrsbhList);
            // 5. 调用Service进行IN查询
            IPage<AjglCfjdsqcEntity> ajglCfjdsqcEntityIPage = ajglCfjdsqcService.queryCfjdsTable(ajglCfjdsqcEntity);
            // 封装返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("pageData", ajglCfjdsqcEntityIPage);  // 分页数据
            result.put("nsrsbhList", nsrsbhList);           // 纳税人识别号列表
            return ResponseEntity.ok(Result.success(result));
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            return ResponseEntity.ok(Result.error("解析文件失败：" + e.getMessage()));
        }
    }


}